<template>
  <div class="home-page">
    <div class="page-container">
      <el-row :gutter="20">
        <el-col :span="16">
          <div class="welcome-card card">
            <h2>欢迎来到元宇宙宠物冒险</h2>
            <p class="mt-4">在这里，你可以：</p>
            <ul class="feature-list">
              <li>领养并培养你自己的虚拟宠物</li>
              <li>完成各种有趣的任务</li>
              <li>提升宠物的等级和属性</li>
              <li>探索更多精彩内容</li>
            </ul>
          </div>
          
          <div class="task-preview card mt-4">
            <div class="card-header">
              <h3>最新任务</h3>
              <router-link to="/tasks" class="view-all-btn">
                <span class="text">查看全部</span>
                <el-icon class="arrow-icon"><ArrowRight /></el-icon>
              </router-link>
            </div>
            
            <el-empty v-if="!tasks.length" description="暂无任务" v-loading="loading" />
            
            <div v-else class="task-list">
              <div v-for="task in tasks" :key="task.id" class="task-item" @click="handleSelectTask(task)">
                <div class="task-info">
                  <h4>{{ task.title }}</h4>
                  <p>{{ task.description }}</p>
                  <div class="task-tags">
                    <el-tag size="small" :type="getTaskTypeColor(task.type)">{{ getTaskTypeLabel(task.type) }}</el-tag>
                    <el-tag size="small" :type="getTaskDifficultyColor(task.difficulty)">{{ getDifficultyLabel(task.difficulty) }}</el-tag>
                  </div>
                </div>
                <div class="task-reward">
                  <div class="reward-item">
                    <el-icon><Star /></el-icon>
                    经验值: {{ task.reward.experience }}
                  </div>
                  <div v-if="task.reward.coins" class="reward-item">
                    <el-icon><Money /></el-icon>
                    金币: {{ task.reward.coins }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-col>

        <el-col :span="8">
          <el-card v-if="!loading">
            <div v-if="pet && pet.userId" class="pet-status">
              <h3>我的宠物</h3>
              <div class="pet-info mt-4 clickable" @click="goToPetDetail">
                <h4>{{ pet.name }}</h4>
                <div class="pet-species text-center mb-2">{{ getPetSpeciesLabel(pet.species) }}</div>
                <div class="pet-stats">
                  <el-progress 
                    :percentage="(pet.experience % 100)" 
                    :format="() => `等级 ${pet.level}`"
                    class="mt-2"
                  />
                  <el-progress 
                    :percentage="pet.hunger"
                    :status="getStatusType(pet.hunger)"
                    class="mt-2"
                  >
                    <template #default="{ percentage }">
                      饥饿值 {{ percentage }}%
                    </template>
                  </el-progress>
                  <el-progress 
                    :percentage="pet.happiness"
                    :status="getStatusType(pet.happiness)"
                    class="mt-2"
                  >
                    <template #default="{ percentage }">
                      心情 {{ percentage }}%
                    </template>
                  </el-progress>
                  <el-progress 
                    :percentage="pet.energy"
                    :status="getStatusType(pet.energy)"
                    class="mt-2"
                  >
                    <template #default="{ percentage }">
                      体力 {{ percentage }}%
                    </template>
                  </el-progress>
                </div>
              </div>
            </div>
            <div v-else class="adopt-prompt">
              <div class="adopt-prompt-icon">🏠</div>
              <h3>还没有宠物？</h3>
              <p>在这里，你可以领养一只可爱的宠物，它将陪伴你一起冒险！</p>
              <el-button type="primary" @click="goToAdopt" class="adopt-button">
                去领养宠物
                <el-icon class="el-icon--right"><ArrowRight /></el-icon>
              </el-button>
            </div>
          </el-card>
          <el-card v-else>
            <div style="text-align:center;padding:40px 0;">加载中...</div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed, watch } from 'vue'
import { useUserStore } from '../stores/user'
import { usePetStore } from '../stores/pet'
import { useTaskStore } from '../stores/task'
import { ArrowRight, Star, Money } from '@element-plus/icons-vue'
import { calculateExpPercentage } from '../utils/helpers'
import PetAdoptPanel from './PetAdoptPanel.vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { http } from '../utils/http'

export default {
  name: 'HomeView',
  components: { 
    PetAdoptPanel,
    Star,
    Money,
    ArrowRight
  },
  setup() {
    const userStore = useUserStore()
    const petStore = usePetStore()
    const taskStore = useTaskStore()
    const router = useRouter()

    const loading = ref(false)
    const tasks = ref([
      {
        id: 1,
        title: '每日问候',
        description: '与你的宠物打招呼开始新的一天',
        type: 'daily',
        difficulty: 'easy',
        reward: {
          experience: 5,
          coins: 10
        },
        isActive: true
      },
      {
        id: 2,
        title: '讲故事时间',
        description: '给你的宠物讲一个睡前故事',
        type: 'story',
        difficulty: 'easy',
        reward: {
          experience: 15,
          coins: 20
        },
        isActive: true
      },
      {
        id: 3,
        title: '基础训练',
        description: '教你的宠物学习基本指令',
        type: 'training',
        difficulty: 'medium',
        reward: {
          experience: 20,
          coins: 30
        },
        isActive: true
      },
      {
        id: 4,
        title: '心情安抚',
        description: '当宠物心情不好时安抚它',
        type: 'interaction',
        difficulty: 'medium',
        reward: {
          experience: 25,
          coins: 40
        },
        isActive: true
      },
      {
        id: 5,
        title: '解决难题',
        description: '帮助宠物解决一个小难题',
        type: 'story',
        difficulty: 'hard',
        reward: {
          experience: 35,
          coins: 50
        },
        isActive: true
      }
    ])

    const user = ref(userStore.user)
    const pet = computed(() => petStore.pet)
    const expPercentage = ref(calculateExpPercentage(user.value?.exp || 0, user.value?.nextLevelExp || 100))

    // 获取最新任务（暂时注释掉，使用静态数据）
    // const fetchLatestTasks = async () => {
    //   try {
    //     loading.value = true
    //     const response = await http.get('/tasks/latest')
    //     if (response?.data?.data?.tasks) {
    //       tasks.value = response.data.data.tasks
    //     }
    //   } catch (error) {
    //     console.error('获取最新任务失败:', error)
    //     ElMessage.error('获取最新任务失败')
    //   } finally {
    //     loading.value = false
    //   }
    // }

    // 处理选择任务
    const handleSelectTask = (task) => {
      router.push({
        path: '/tasks',
        query: { selected: task.id }
      })
    }

    // 状态条颜色映射
    const getStatusType = (value) => {
      if (value >= 70) return 'success'
      if (value >= 40) return 'warning'
      return 'exception'
    }

    // 宠物种类标签
    const getPetSpeciesLabel = (species) => {
      const labels = {
        cat: '猫咪',
        dog: '狗狗',
        rabbit: '兔子',
        hamster: '仓鼠',
        parrot: '鹦鹉'
      }
      return labels[species] || species
    }

    const goToPetDetail = () => {
      router.push('/pet')
    }

    const goToAdopt = () => {
      router.push('/pet')
    }

    const getTaskTypeColor = (type) => {
      const colors = {
        daily: 'success',
        story: 'warning',
        training: 'primary',
        interaction: 'info'
      }
      return colors[type] || 'info'
    }

    const getTaskTypeLabel = (type) => {
      const labels = {
        daily: '日常任务',
        story: '剧情任务',
        training: '训练任务',
        interaction: '互动任务'
      }
      return labels[type] || type
    }

    const getTaskDifficultyColor = (difficulty) => {
      const colors = {
        easy: 'success',
        medium: 'warning',
        hard: 'danger'
      }
      return colors[difficulty] || 'info'
    }

    const getDifficultyLabel = (difficulty) => {
      const labels = {
        easy: '简单',
        medium: '中等',
        hard: '困难'
      }
      return labels[difficulty] || difficulty
    }

    onMounted(async () => {
      // await fetchLatestTasks()
    })

    // 监听路由变化，重新加载数据
    watch(() => router.currentRoute.value.path, (newPath) => {
      if (newPath === '/') {
        // fetchLatestTasks()
      }
    })

    return {
      loading,
      tasks,
      user,
      pet,
      expPercentage,

      getStatusType,
      getPetSpeciesLabel,
      goToPetDetail,
      goToAdopt,
      ArrowRight,
      handleSelectTask,
      getTaskTypeColor,
      getTaskTypeLabel,
      getTaskDifficultyColor,
      getDifficultyLabel
    }
  }
}
</script>

<style scoped>
.adopt-prompt {
  text-align: center;
  padding: 40px 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7eb 100%);
  border-radius: 16px;
  transition: all 0.3s ease;
}

.adopt-prompt:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.adopt-prompt-icon {
  font-size: 48px;
  margin-bottom: 20px;
  animation: float 3s ease-in-out infinite;
}

.adopt-prompt h3 {
  font-size: 24px;
  color: #303133;
  margin-bottom: 12px;
  font-weight: 600;
}

.adopt-prompt p {
  font-size: 16px;
  color: #606266;
  margin-bottom: 24px;
  line-height: 1.6;
}

.adopt-button {
  padding: 12px 24px;
  font-size: 16px;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
}

.adopt-button:hover {
  transform: translateX(5px);
}

@keyframes float {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-10px);
  }
}
.feature-list {
  list-style-type: none;
  padding: 0;
  margin: 20px 0;
}

.feature-list li {
  margin: 10px 0;
  padding-left: 24px;
  position: relative;
}

.feature-list li::before {
  content: "✨";
  position: absolute;
  left: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.view-all-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  color: var(--el-color-primary);
  text-decoration: none;
  font-size: 14px;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s ease;
  background: rgba(64, 158, 255, 0.1);
}

.view-all-btn:hover {
  background: rgba(64, 158, 255, 0.2);
  transform: translateX(2px);
}

.arrow-icon {
  transition: transform 0.3s ease;
}

.view-all-btn:hover .arrow-icon {
  transform: translateX(2px);
}

.task-list {
  margin-top: 20px;
}

.task-item {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 15px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s;
  cursor: pointer;
}

.task-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.task-info h4 {
  margin: 0;
  font-size: 18px;
  color: var(--el-text-color-primary);
  margin-bottom: 8px;
}

.task-info p {
  margin: 0;
  color: var(--el-text-color-regular);
  font-size: 14px;
  line-height: 1.5;
}

.task-tags {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
}

.task-reward {
  display: flex;
  gap: 16px;
  margin-top: 16px;
  padding-top: 12px;
  border-top: 1px solid #ebeef5;
}

.reward-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #67c23a;
  font-size: 14px;
}

.reward-item .el-icon {
  font-size: 18px;
  color: #f7ba2a;
}

.pet-avatar {
  width: 120px;
  height: 120px;
  border-radius: 60px;
  display: block;
  margin: 0 auto;
}

.pet-info h4 {
  text-align: center;
  margin: 15px 0;
}

.pet-stats {
  padding: 0 10px;
}

.clickable {
  cursor: pointer;
  transition: box-shadow 0.2s, background 0.2s;
}
.clickable:hover {
  background: #f5f7fa;
  box-shadow: 0 2px 8px rgba(64,158,255,0.08);
}
</style>
